package service

import (
	"github.com/astaxie/beego/orm"
	"net/url"
	"xianzhi/models"
	"xianzhi/utils"
)

// 获取权限信息
func GetAuthorityInfo(p map[string]interface{}) *models.Authority {
	o := orm.NewOrm()
	authority := &models.Authority{}
	qs := o.QueryTable("Authority")
	if _, ok := p["relation"]; ok && p["relation"].(bool) {
		qs = qs.RelatedSel()
	}
	if _, ok := p["id"]; ok {
		qs = qs.Filter("id", p["id"])
	}
	qs.One(authority)
	return authority
}

// 添加权限信息
func AddAuthority(input url.Values) (int64, error) {
	o := orm.NewOrm()
	authority := &models.Authority{}
	authorityCategory := &models.AuthorityCategory{}
	if _, ok := input["authority_category_id"]; ok {
		authorityCategory.Id = utils.Atoi64(input["authority_category_id"][0])
		o.Read(authorityCategory)
	}
	authority.AuthorityCategory = authorityCategory
	if _, ok := input["name"]; ok {
		authority.Name = input["name"][0]
	}
	if _, ok := input["rule"]; ok {
		authority.Rule = input["rule"][0]
	}
	return o.Insert(authority)
}

// 修改权限信息
func EditAuthority(input url.Values) (int64, error) {
	o := orm.NewOrm()
	p := orm.Params{}
	for k, v := range input {
		if k == "id" || k == "_xsrf" {
			continue
		}
		p[k] = v[0]
	}
	return o.QueryTable("Authority").Filter("id", input["id"][0]).Update(p)
}

// 获取权限列表
func GetAuthorityList(p map[string]interface{}) (int64, []*models.Authority) {
	var authorityList []*models.Authority
	o := orm.NewOrm()
	qs := o.QueryTable("Authority")
	if _, ok := p["relation"]; ok && p["relation"].(bool) {
		qs = qs.RelatedSel()
	}
	if _, ok := p["authorityCategoryId"]; ok {
		qs = qs.Filter("authority_category_id", p["authorityCategoryId"])
	}
	if _, ok := p["userAdminRoleId"]; ok {
		qs = qs.Filter("UserAdminRoles__UserAdminRole__Id", p["userAdminRoleId"])
	}
	totalCount, _ := qs.Count()
	curPage, ok := p["curPage"]
	perCount, _ := p["perCount"]
	if ok {
		start := perCount.(int) * (curPage.(int) - 1)
		qs = qs.Limit(perCount, start)
	}
	qs.All(&authorityList)
	return totalCount, authorityList
}